package org.weather;

import java.net.URI;
import java.net.URL;

import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Activitatea care arată vremea. Este chemată prin intent când un utilizator
 * apasă pe un oraș din listă.
 * @author andrei
 *
 */

public class WeatherReport extends Activity implements OnClickListener {
	TextView title;
	TextView forecastDate;
	TextView humidity;
	TextView tempC;
	TextView wind;
	TextView condition;
	/*folosite pentru prognoza pe urmatoarele zile*/
	TextView[] day;
	ImageView[] icon;
	/*buton de iesire din aplicatie*/
	Button exit;

	/**
	 * In onCreate se creeaza toate elementele pentru afisarea vremii pentru un
	 * oras selectat si trimis print intent de la WeatherActivity.
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.report);

		day = new TextView[4];
		icon = new ImageView[5];

		title = (TextView) findViewById(R.id.title);
		forecastDate = (TextView) findViewById(R.id.forecast_date);
		condition = (TextView) findViewById(R.id.condition);
		tempC = (TextView) findViewById(R.id.temp_c);
		humidity = (TextView) findViewById(R.id.humidity);
		wind = (TextView) findViewById(R.id.wind);
		icon[0] = (ImageView) findViewById(R.id.icon);

		day[0] = (TextView) findViewById(R.id.day1);
		day[1] = (TextView) findViewById(R.id.day2);
		day[2] = (TextView) findViewById(R.id.day3);
		day[3] = (TextView) findViewById(R.id.day4);

		icon[1] = (ImageView) findViewById(R.id.icon1);
		icon[2] = (ImageView) findViewById(R.id.icon2);
		icon[3] = (ImageView) findViewById(R.id.icon3);
		icon[4] = (ImageView) findViewById(R.id.icon4);

		exit = (Button) findViewById(R.id.exit_report);
		exit.setOnClickListener(this);

		String cityName = getIntent().getStringExtra("name");
		
		Log.println(Log.DEBUG, "evenimente", "Retrieving for " + cityName);
		
		/*este folosit pentru e extrage datele din campurile xml-ului*/
		String dummy = "";
		/*afisam toate datele pentru urmatoarele zile intr-un singur string*/
		String dayText[] = new String[4];

		int i;

		for (i = 0; i < 4; i++) {
			dayText[i] = "";
		}

		try {
			/*ca sa putem cauta si New York, nu doar Paris
			 * (orase cu nume compus)*/
			URI uri = new URI(
			        "http",
			        "www.google.com",
			        "/ig/api",
			        "weather=" + cityName,
			        null);
			String request = uri.toASCIIString();

			URL url = new URL(request);
			
			/*incepem sa parsam*/
			Document doc = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder()
					.parse(new InputSource(url.openStream()));

			doc.getDocumentElement().normalize();
			
			/*bunicul xml*/
			Element weather = (Element) doc.getElementsByTagName("weather")
					.item(0);

			Element aux;
			NodeList auxList;

			/*vedem daca avem probleme*/ 
			auxList = weather.getElementsByTagName("problem_cause");
			
			if (auxList.getLength() == 0) {
				
				title.setText(cityName);

				aux = (Element) weather.getElementsByTagName("forecast_date")
						.item(0);
				dummy = aux.getAttribute("data");
				if (dummy != "") {
					forecastDate.setText(dummy);
				} else {
					forecastDate.setText("CANNOT FIND DATE");
				}

				aux = (Element) weather.getElementsByTagName("temp_c").item(0);
				dummy = aux.getAttribute("data");
				if (dummy != "") {
					tempC.setText(dummy + " degrees C");
				} else {
					tempC.setText("CANNOT FIND TEMPERATURE");
				}

				aux = (Element) weather.getElementsByTagName("humidity")
						.item(0);
				dummy = aux.getAttribute("data");
				if (dummy != "") {
					humidity.setText(dummy);
				} else {
					humidity.setText("CANNOT FIND HUMIDITY");
				}

				aux = (Element) weather.getElementsByTagName("wind_condition")
						.item(0);
				dummy = aux.getAttribute("data");
				if (dummy != "") {
					wind.setText(dummy);
				} else {
					wind.setText("CANNOT FIND WIND CONDITION");
				}

				auxList = weather.getElementsByTagName("day_of_week");
				for (i = 0; i < auxList.getLength(); i++) {
					dayText[i] += ((Element) auxList.item(i))
							.getAttribute("data");
					dayText[i] += " ";
				}

				auxList = weather.getElementsByTagName("low");
				for (i = 0; i < auxList.getLength(); i++) {
					dummy = ((Element) auxList.item(i)).getAttribute("data");
					int fahr = Integer.parseInt(dummy);
					dayText[i] += "" + (int) ((fahr - 32) * 5 / 9) + "C ";
				}

				auxList = weather.getElementsByTagName("condition");

				condition.setText(((Element) auxList.item(0))
						.getAttribute("data"));

				for (i = 1; i < auxList.getLength(); i++) {
					dayText[i - 1] += ((Element) auxList.item(i))
							.getAttribute("data");
				}

				for (i = 0; i < 4; i++) {
					day[i].setText(dayText[i]);
					Log.println(Log.DEBUG, "evenimente", dayText[i]);
				}

				auxList = weather.getElementsByTagName("icon");
				Log.println(Log.DEBUG, "evenimente",
						"nr poze " + auxList.getLength());
				for (i = 0; i < auxList.getLength(); i++) {
					dummy = ((Element) auxList.item(i)).getAttribute("data");

					dummy = parseIcon(dummy);
					Log.println(Log.DEBUG, "evenimente", "nume poza " + dummy);
					Log.println(Log.DEBUG, "evenimente", "" + setIcon(i, dummy));
				}
			}else{
				title.setText(cityName + " not found");
			}
		} catch (Exception e) {
			System.out.println("XML Pasing Expetion = " + e);
		}

	}

	/**
	 * Metoda extrage din string numele pozei, care este folosit in setIcon.
	 * 
	 * @param url
	 * @return
	 */
	public String parseIcon(String url) {
		StringTokenizer st = new StringTokenizer(url, "/");
		String pic = "";
		while (st.hasMoreTokens()) {
			pic = st.nextToken();
		}
		st = new StringTokenizer(pic, ".");
		pic = st.nextToken();
		return pic;
	}

	/**
	 * Metoda incarca o poza corespunzatoare vremii.
	 * 
	 * @param index
	 *            indexul iconitei din vectorul de iconite
	 * @param text
	 *            textul extras din xml referitor la iconita
	 * @return true daca a setat iconita
	 */
	public boolean setIcon(int index, String text) {
		if (text.compareTo("chance_of_rain") == 0) {
			icon[index].setBackgroundResource(R.drawable.chance_of_rain);
			return true;
		}
		if (text.compareTo("chance_of_snow") == 0) {
			icon[index].setBackgroundResource(R.drawable.chance_of_snow);
			return true;
		}
		if (text.compareTo("chance_of_storm") == 0) {
			icon[index].setBackgroundResource(R.drawable.chance_of_storm);
			return true;
		}
		if (text.compareTo("chance_of_tstorm") == 0) {
			icon[index].setBackgroundResource(R.drawable.chance_of_tstorm);
			return true;
		}
		if (text.compareTo("cloudy") == 0) {
			icon[index].setBackgroundResource(R.drawable.cloudy);
			return true;
		}
		if (text.compareTo("dust") == 0) {
			icon[index].setBackgroundResource(R.drawable.dust);
			return true;
		}
		if (text.compareTo("flurries") == 0) {
			icon[index].setBackgroundResource(R.drawable.flurries);
			return true;
		}
		if (text.compareTo("fog") == 0) {
			icon[index].setBackgroundResource(R.drawable.fog);
			return true;
		}
		if (text.compareTo("haze") == 0) {
			icon[index].setBackgroundResource(R.drawable.haze);
			return true;
		}
		if (text.compareTo("icy") == 0) {
			icon[index].setBackgroundResource(R.drawable.icy);
			return true;
		}
		if (text.compareTo("mist") == 0) {
			icon[index].setBackgroundResource(R.drawable.mist);
			return true;
		}
		if (text.compareTo("mostly_cloudy") == 0) {
			icon[index].setBackgroundResource(R.drawable.mostly_cloudy);
			return true;
		}
		if (text.compareTo("mostly_sunny") == 0) {
			icon[index].setBackgroundResource(R.drawable.mostly_sunny);
			return true;
		}
		if (text.compareTo("partly_cloudy") == 0) {
			icon[index].setBackgroundResource(R.drawable.partly_cloudy);
			return true;
		}
		if (text.compareTo("rain") == 0) {
			icon[index].setBackgroundResource(R.drawable.rain);
			return true;
		}
		if (text.compareTo("sleet") == 0) {
			icon[index].setBackgroundResource(R.drawable.sleet);
			return true;
		}
		if (text.compareTo("smoke") == 0) {
			icon[index].setBackgroundResource(R.drawable.smoke);
			return true;
		}
		if (text.compareTo("snow") == 0) {
			icon[index].setBackgroundResource(R.drawable.snow);
			return true;
		}
		if (text.compareTo("storm") == 0) {
			icon[index].setBackgroundResource(R.drawable.storm);
			return true;
		}
		if (text.compareTo("sunny") == 0) {
			icon[index].setBackgroundResource(R.drawable.sunny);
			return true;
		}
		if (text.compareTo("thunderstorm") == 0) {
			icon[index].setBackgroundResource(R.drawable.thunderstorm);
			return true;
		}
		return false;
	}

	/**
	 * Buton de iesire din aplicatie.
	 */
	@Override
	public void onClick(View v) {
		finish();
	}
}
